/**
* Author: Samfu
* Time  : 下午11:49:09
* Desc  : 
*/
package com.samfu.main;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;

import com.samfu.util.Constants;

public class StringReplaceMain {

	// 遍历目录
	private static ArrayList<String> fileList = new ArrayList<>();

	// 通过递归得到指定目录下的目录及文件
	private static ArrayList<String> getFiles(String filePath) {
		File root = new File(filePath);
		File[] files = root.listFiles();
		for (File file : files) {
			if (file.isDirectory()) {
				// 递归调用
				getFiles(file.getAbsolutePath());
			} else {
				//过滤掉class, jar, jpg/png/gif文件
				if (file.getName().endsWith("class") || file.getName().endsWith("jar")
						|| file.getName().endsWith("jpg") || file.getName().endsWith("png")
						||file.getName().endsWith("gif")) {
					continue;
				} else {
					fileList.add(file.getAbsolutePath());			
				}				
			}
		}
		return fileList;
	}
	// 执行替换
	private static void replaceStr(ArrayList<String> list) {
		
		Iterator iterator = list.iterator();
		String filePath = "";
		while (iterator.hasNext()) {
			filePath = iterator.next().toString();
			System.out.println("处理file： " + filePath);
			replaceExecutor(filePath);
		}
	}
	
	private static void replaceExecutor(String fileAbsolutepath) {
		String temp = "";
		File file = new File(fileAbsolutepath);
		try {
			FileInputStream fis = new FileInputStream(file);
			InputStreamReader isr = new InputStreamReader(fis,"gbk");
			BufferedReader br = new BufferedReader(isr);
			StringBuffer buffer = new StringBuffer();
			
			//保存该行前面的内容
			for (int j=0; (temp=br.readLine())!=null && !temp.equals(Constants.tobeReplaceStr); j++) {
				//System.out.println("找到相应的内容 " + Constants.tobeReplaceStr);
				buffer = buffer.append(temp);
				buffer = buffer.append(System.getProperty("line.separator"));
			}
			
			//将内容插入
			buffer = buffer.append(Constants.replaceWithStr);
			
			//保存该行后面的内容
			while ((temp=br.readLine())!=null) {
				buffer = buffer.append(System.getProperty("line.separator"));
				buffer = buffer.append(temp);
			}
			br.close();
//			FileOutputStream fos = new FileOutputStream(file);
//			PrintWriter pw = new PrintWriter(fos);
//			pw.write(buffer.toString());
//			pw.flush();
//			pw.close();
			BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
				    new FileOutputStream(file), "gbk"));
			writer.write(buffer.toString());
			writer.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	
	public static void main(String[] args) {
		StringReplaceMain.getFiles(Constants.folder);
		StringReplaceMain.replaceStr(fileList);
	}
}
